<script setup>
import { ref } from 'vue'
import { policiesGetDetailService, policiesPutService } from '@/api/policies'
import { useRoute } from 'vue-router'
import { insertTab, checkPoliciesContent } from '@/utils/policies'

const route = useRoute()

// 接收传递参数
const policyId = route.query.id
const policyName = route.query.name

// 修改策略内容
const form = ref()

const formModel = ref({
  content: ''
})

const rules = {
  content: [
    { required: true, message: '策略内容不能为空！', trigger: 'submit'},
    { 
      validator: (rule, value, callback) => {
        checkPoliciesContent(value, callback)
      },
      trigger: 'submit'  
    }
  ]
}

const updatePolicy = async () => {
  await form.value.validate()
  const content = JSON.stringify(JSON.parse(formModel.value.content), null, 0)
  await policiesPutService(policyId, content)
}

// 获取策略详细内容
const getPolicyDetail = async () => {
  const res = await policiesGetDetailService(policyId)
  const content = res.data.data

  formModel.value.content = JSON.stringify(JSON.parse(content), null, 4)
}
getPolicyDetail()


</script>

<template>
  <el-container>
    <el-header style="border-bottom: 1px solid rgb(229, 229, 229)">
      <div style="display: flex; align-items: center;">
        <el-icon size="50" style="margin-right: 5px;">
          <svg t="1733367675151" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="13948"><path d="M512 108.7488S296.192 251.3408 168.1408 173.7216c-2.9184 0 21.3504 484.9664 60.1088 562.5856 38.8096 77.6192 283.6992 178.944 283.6992 178.944s240.0768-98.9184 281.088-178.944c41.0112-80.0256 60.8256-560.64 63.0272-562.5856C713.216 258.0992 512 108.7488 512 108.7488z m78.0288 396.032v28.2112h-60.3136v49.8176l48.4864 21.7088v15.4112h-48.4864v80.5376l-36.0448 48.7936V442.3168c-36.0448-8.2944-62.9248-40.4992-62.9248-79.104 0-44.8512 36.352-81.2544 81.2544-81.2544s81.2544 36.352 81.2544 81.2544c0 38.7584-27.136 71.1168-63.488 79.2064v62.3104h60.2624z" p-id="13949"></path></svg>
        </el-icon>
        <div>
          <div style="font-size: 22px;"><strong>{{ policyName }}</strong></div>
          <div><el-text size="small">IAM 策略</el-text></div>
        </div>
      </div>
    </el-header>
    <el-main>
      <div style="border: 1px solid rgb(229, 229, 229); padding: 15px;">
        <el-form ref="form" :model="formModel" :rules="rules"  @submit.prevent>
          <el-form-item prop="content">
            <el-input v-model="formModel.content" @keydown.tab.prevent="insertTab" name="content" type="textarea" resize="none" :autosize="{minRows: 18}" />
          </el-form-item>
          <el-form-item>
            <div style="display: flex; justify-content: flex-end; width: 100%;">
              <el-button @click="updatePolicy" color="black">保存</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-main>
  </el-container>

</template>

<style lang="sass" scoped>
</style>